from django.db import models
import re ,os
from django.core.exceptions import ValidationError
# Create your models here.

def validate_even(value):
    if not (re.search("^MP_verify_",value.name) and re.search(".txt$",value.name)):
        raise ValidationError(
            ('%(value)s is invalid.'),
            params={'value': value.name},
        )

class VerifyHost(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=10,unique=True)
    website = models.CharField(max_length=100)
    ansible_group = models.CharField(max_length=50)
    dest = models.CharField(max_length=100)
    desc = models.CharField(max_length=100,blank=True,null=True)


def upload_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'wechatverifyupload/wechat-keys/{0}/{1}'.format(instance.host.id, filename)

class WechatVerify(models.Model):
    id = models.AutoField(primary_key=True)
    host = models.ForeignKey(VerifyHost)
    file = models.FileField(upload_to=upload_directory_path,validators=[validate_even])
    desc = models.CharField(max_length=50,blank=True,null=True)

    def delete(self, *args, **kwargs):
        if os.path.isfile(self.file.path):
            os.remove(self.file.path)
        super(WechatVerify, self).delete(*args, **kwargs)
    class Meta:
        permissions = (
            ("wechatverifyupload_admin", "wechatverifyupload Admin 权限"),
        )